<?php

namespace App\Services\Admin;

use App\Services\Service;
use App\Models\DictItem;
use App\Models\Dict;

class DictItemService extends Service
{

    public static function options(string $dictCode): array
    {
        $dict = Dict::where('dictCode', $dictCode)->firstOrFail();

        $list = $dict->dictItems()->orderBy('sort', 'asc')->get()->toArray();

        $list = array_map(fn($item) => [
            'value'   => $item['value'],
            'label'   => $item['label'],
            'tagType' => $item['tagType']
        ], $list);

        return $list;
    }


    public static function index(array $params, string $dictCode): array
    {
        $dict = Dict::where('dictCode', $dictCode)->firstOrFail();

        $query = $dict->dictItems()->orderBy('sort', 'asc');

        $pageNum = $params['pageNum'];
        $pageSize = $params['pageSize'];

        $paginator = $query->paginate($pageSize, ['*'], 'page', $pageNum);

        $paginator->getCollection()->makeVisible(['createTime', 'updateTime']);

        return [
            'list'  => $paginator->items(),
            'total' => $paginator->total(),
        ];
    }

    public static function store(array $data, string $dictCode): array
    {

        $dict = Dict::where('dictCode', $dictCode)->firstOrFail();

        $dict_item = $dict->dictItems()->create($data);

        return [
            'id' => $dict_item->id
        ];
    }

    public static function show(string $dictCode, string $id): array
    {

        $dict = Dict::where('dictCode', $dictCode)->firstOrFail();

        if (!$dict) {
            self::throwValidationException('id', ['字典不存在']);
        }

        $dictItem = $dict->dictItems()->findOrFail($id);

        if (!$dictItem) {
            self::throwValidationException('id', ['字典不存在']);
        }

        return $dictItem->toArray();
    }


    public static function update(array $data, string $dictCode, string $id): array
    {

        $dict = Dict::where('dictCode', $dictCode)->firstOrFail();

        if (!$dict) {
            self::throwValidationException('id', ['字典不存在']);
        }

        $dictItem = $dict->dictItems()->findOrFail($id);

        if (!$dictItem) {
            self::throwValidationException('id', ['字典不存在']);
        }

        $dictItem->update($data);

        return [
            'id' => $dictItem->id
        ];
    }

    public static function destroy(string $dictCode, string $id): array
    {

        $dict = Dict::where('dictCode', $dictCode)->firstOrFail();

        if (!$dict) {
            self::throwValidationException('id', ['字典不存在']);
        }

        $dictItem = $dict->dictItems()->findOrFail($id);

        if (!$dictItem) {
            self::throwValidationException('id', ['字典不存在']);
        }

        $dictItem->delete();

        return [
            'id' => $dictItem->id
        ];
    }
}
